package trystero.lib.component.parser;

import java.util.Hashtable;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONTokener;

import trystero.lib.component.UnreadCount;

public class UnreadCountParser
{
   InputStream stream;

   public UnreadCountParser(InputStream stream)
   {
      this.stream = stream;
   }

   public UnreadCount parse() throws Exception
   {
      JSONTokener t = new JSONTokener(new InputStreamReader(this.stream));
      JSONObject o = new JSONObject(t);
      return this.parse(o);
   }

   public UnreadCount parse(JSONObject o) throws Exception
   {
      UnreadCount u = new UnreadCount();

      u.max((Integer)o.get("max"));

      JSONArray unread = (JSONArray)o.get("unreadcounts");

      Hashtable counts = new Hashtable();
      Hashtable timestamps = new Hashtable();

      for(int i = 0; i < unread.length(); i++)
      {
	 JSONObject item = (JSONObject)unread.get(i);
	 counts.put(item.get("id"), item.get("count"));
	 timestamps.put(item.get("id"), item.get("newestItemTimestampUsec"));
      }

      u.counts(counts);
      u.timestamps(timestamps);

      return u;
   }
}
